package com.ksd.modules.login.controller;

import com.google.code.kaptcha.Constants;
import com.ksd.common.annotation.ApiLog;
import com.ksd.common.annotation.LoginIgnore;
import com.ksd.common.controller.BaseController;
import com.ksd.common.core.result.R;
import com.ksd.common.web.threadlocal.UserIdThrealLocal;
import com.ksd.modules.rbac.sysuser.context.UserLoginContext;
import com.ksd.modules.rbac.sysuser.po.UserLoginPO;
import com.ksd.modules.rbac.sysuser.service.ISysUsersService;
import com.ksd.utils.aes.DesUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author 飞哥
 * @date 2023-08-14$ 0:04$
 */
@RestController
public class LoginController extends BaseController {

    @Resource
    private ISysUsersService sysUsersService;

    @ApiOperation(
            value = "后台用户登录接口",
            notes = "该接口提供了用户登录的功能，成功登陆之后，会返回有时效性的accessToken供后续服务使用"
    )
    @LoginIgnore
    @PostMapping("login/toLogin")
    @ApiLog("后台用户登录接口")
    public R<UserLoginContext> login(@Validated @RequestBody UserLoginPO userLoginPO, HttpSession session) {
        String sessionCode =  (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        UserLoginContext userLoginContext = new UserLoginContext();
                BeanUtils.copyProperties(userLoginPO, userLoginContext);
        userLoginContext.setSessionCode(sessionCode);
        String accessToken = sysUsersService.login(userLoginContext);
        userLoginContext.setAccessToken(DesUtils.encrypt(accessToken));
        return R.data(userLoginContext);
    }

    @ApiOperation(
            value = "用户登出接口",
            notes = "该接口提供了用户登出的功能",
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE
    )
    @PostMapping("login/logout")
    @ApiLog("用户登出接口")
    @LoginIgnore
    public R exit() {
        sysUsersService.exit(UserIdThrealLocal.get().getUserId());
        return R.success();
    }
}
